const mysql = require('mysql2/promise');
const config = require('../config');

class Database {
  constructor() {
    this.pool = mysql.createPool(config.database);
  }

  // 执行查询操作
  async query(sql, params) {
    const [rows, fields] = await this.pool.execute(sql, params);
    return rows;
  }

  // 插入数据
  async insert(table, data) {
    const keys = Object.keys(data);
    const values = Object.values(data);
    const sql = `INSERT INTO ${table} (${keys.join(', ')}) VALUES (${keys.map(() => '?').join(', ')})`;
    await this.query(sql, values);
  }

  // 更新数据
  async update(table, data, where) {
    const keys = Object.keys(data);
    const values = Object.values(data);
    const sql = `UPDATE ${table} SET ${keys.map((key) => `${key} = ?`).join(', ')} WHERE ${where}`;
    await this.query(sql, values);
  }

  // 删除数据
  async delete(table, where) {
    const sql = `DELETE FROM ${table} WHERE ${where}`;
    await this.query(sql);
  }

  // 查询数据
  async select(table, where, columns = ['*'], orderBy = '', limit = '') {
    let sql = `SELECT ${columns.join(', ')} FROM ${table} WHERE ${where}`;
    if (orderBy) {
      sql += ` ORDER BY ${orderBy}`;
    }
    if (limit) {
      sql += ` LIMIT ${limit}`;
    }
    const rows = await this.query(sql);
    return rows;
  }

  // 关闭连接池
  async close() {
    await this.pool.end();
  }
}

module.exports = Database;